package com.zj.project.common.base

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.zj.project.bean.ArticleItemBean
import com.zj.project.common.http.Api
import retrofit2.HttpException
import java.io.IOException

class BaseDataSource<T : Any>(val api: Api) : PagingSource<Int, ArticleItemBean>() {

    override fun getRefreshKey(state: PagingState<Int, ArticleItemBean>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleItemBean> {
        return try {
            val currentPage = params.key ?: 1
            val data = api.getArticle(currentPage).data
            //当前页码 小于 总页码 页面加1
            val nextPage = if (currentPage < data.pageCount ?: 0) {
                currentPage + 1
            } else {
                //没有更多数据
                null
            }
            LoadResult.Page(
                data = data.datas,
                prevKey = null,
                nextKey = nextPage
            )
        } catch (e: IOException) {
            LoadResult.Error(e)
        } catch (e: HttpException) {
            LoadResult.Error(e)
        }
    }


}